import os

from neo4j import GraphDatabase
from ..config.config import Config

class WirteNeo4j:
	def __init__(self):
		#初始化化neo4j驱动程序
		self.driver = GraphDatabase.driver(**Config.NEO4J_CONFIG)
		#实例化config
		self.config = Config()

	def load_data(self):
		"""
		加载审核之后的数据
		:return: {"疾病1" : ["症状1, 症状2，...],
				  "疾病2" : []
				  ...}
		"""
		#读取所有文件名，获取所有疾病名称
		disease_csv_list = os.listdir(self.config.reviewed_path)
		#分割所有文件名取得名称
		disease_list = list(map(lambda x: x.split(".")[0], disease_csv_list))
		# 获取文件内容，也就是症状名称
		symptom_list = []
		for csv in disease_csv_list:
			# symptom = list(map(lambda x: x.strip(),
			# fileinput.FileInput(os.path.join(self.config.reviewed_path, csv))))
			with open(os.path.join(self.config.reviewed_path, csv), 'r', encoding="utf-8") as f:
				symptom = [line.strip() for line in f]
			symptom = list(filter(lambda x: 0 < len(x) < 100, symptom))
			symptom_list.append(symptom)
		# 构造成字典...
		return dict(zip(disease_list, symptom_list))

	def write_to_neo4j(self, disease_symptom_dict):
		"""
		把接收的字典数据, {疾病1:[症状1,症状2,...],疾病2:[症状3,症状4,...],...}，写入到neo4j中
		:return: None
		"""
		with self.driver.session() as session:
				# 外层循环取出每个疾病名称
				for key, value in disease_symptom_dict.items():
					# 创建疾病节点
					cypher = "MERGE (a:Disease{name:%r}) RETURN a" % key
					session.run(cypher)

					# 内层循环取出每个症状名称
					for v in value:
						# 创建症状的节点
						cypher = "MERGE (b:Symptom{name:%r}) RETURN b" % v
						session.run(cypher)
						# 创建疾病节点和症状节点关系
						cypher = "MATCH (a:Disease{name:%r}) MATCH (b:Symptom{name:%r}) WITH a,b MERGE(a)-[r:dis_to_sym]-(b)" % (
						key, v)
						session.run(cypher)
				# 创建索引
				# 分别对疾病和症状创建索引
				cypher = "CREATE INDEX ON:Disease(name)"
				session.run(cypher)
				cypher = "CREATE INDEX ON:Symptom(name)"
				session.run(cypher)